<template>
  <div class="notes-wrapper">
    <!-- 左侧用户概况 -->
    <div class="notes-left" v-if="user">
      <div class="user">
        <img src="@/assets/img/card_bg.jpg" />
        <div class="left-content">
          <div class="top-box">
            <Avatar :src="user.avatar" size="large" />
            {{user.nickname}}
          </div>
          <div class="bottom-box">
            <div class="count-item">
              动态
              <br />
              <span>{{user.note_count}}</span>
            </div>
            <div class="count-item">
              粉丝
              <br />
              <span>{{user.fan_count}}</span>
            </div>
            <div class="count-item">
              关注
              <br />
              <span>{{user.follow_count}}</span>
            </div>
          </div>
        </div>
      </div>

      <div class="comments">
        <Card :bordered="false" dis-hover>
          <p slot="title">最新评论</p>
          <List v-for="item in lastestComment" :key="item.id">
            <ListItem v-for="comment in item.comment" :key="comment.id">
              <ListItemMeta :title="textCut(item.content)">
                <template slot="description">{{comment.user.nickname}}:{{comment.content}}</template>
              </ListItemMeta>
            </ListItem>
          </List>
        </Card>
      </div>
    </div>

    <div class="notes-main">
      <!-- 发布手记 -->
      <div class="notes-main-p1">
        <Input v-model="noteContent" type="textarea" :rows="6" placeholder="有什么想和大家分享的？" />

        <div class="publish-box">
          <div class="publish-left">
            <!-- 上传图片 -->
            <Poptip placement="bottom">
              <Icon custom="iconfont icon-xiangce" size="24" color="#515151" />
              <div slot="content" class="upload-box">
                <div class="upload-list" v-for="(item,index) in uploadList" :key="index">
                  <template v-if="item">
                    <img :src="item" />
                    <div class="upload-list-cover">
                      <Icon type="ios-eye-outline" @click.native="handleUploadPreview(item)"></Icon>
                      <Icon type="ios-trash-outline" @click.native="handleRemove(item)"></Icon>
                    </div>
                  </template>
                </div>
                <Upload
                  ref="upload"
                  :show-upload-list="false"
                  :on-success="handleSuccess"
                  :format="['jpg','jpeg','png']"
                  :max-size="2048"
                  :on-format-error="handleFormatError"
                  :on-exceeded-size="handleMaxSize"
                  :before-upload="handleBeforeUpload"
                  multiple
                  type="drag"
                  :action="'/api/note/' + user.id"
                  style="width: 60px;height: 60px"
                >
                  <div id="upload-button">
                    <Icon type="ios-cloud-upload-outline" size="24"></Icon>
                    <br />上传
                  </div>
                </Upload>
                <Modal v-model="uploadPreview" footer-hide>
                  <img :src="imgUrl" v-if="uploadPreview" style="width: 100%" />
                </Modal>
              </div>
            </Poptip>

            <!-- 交流圈选择 -->
            <Poptip placement="bottom">
              <Icon custom="iconfont icon-huati" size="24" color="#515151" />
              <div slot="content">
                <Option
                  @click.native="onOptionSelected(item.id,item.title)"
                  v-for="item in zoneList"
                  :value="item.id"
                  :key="item.id"
                >{{ item.title }}</Option>
              </div>
            </Poptip>
            <Tag v-if="noteZone.id" closable @on-close="handleTagClose">#{{noteZone.title}}</Tag>
          </div>
          <div class="publish-right">
            <Button type="primary" ghost @click="handleReset()">重置</Button>
            <Button type="primary" @click="handleSubmit()" :loading="loading">
              <span v-if="!loading">
                <Icon type="md-paper-plane" />发布
              </span>
              <span v-else>发布中...</span>
            </Button>
          </div>
        </div>
      </div>

      <!-- 手记列表 -->
      <div class="notes-main-p2">
        <List item-layout="vertical" split :loading="loading">
          <ListItem v-for="(item, index) in noteList.data" :key="index">
            <ListItemMeta
              :avatar="item.user.avatar"
              :title="item.user.nickname"
              :description="item.create_time"
            >
              <template slot="description">
                <Time :time="item.create_time" />
              </template>
            </ListItemMeta>
            {{ item.content}}
            <br />
            <Tag>#{{item.zone.title}}</Tag>
            <div class="list-action">
              <div>
                <Icon type="md-thumbs-up" size="18" @click="handleThumbsUp()" />
                {{item.like_count}}
              </div>
              <Divider type="vertical" />
              <div>
                <Icon
                  type="ios-chatbubbles"
                  size="17"
                  @click="handleShowComments(item.id.toString())"
                />
                {{item.comment_count}}
              </div>
            </div>

            <!-- 手记列表右侧图片展示区 -->
            <template slot="extra">
              <!-- 单张图片 -->
              <img
                :src="parseImgList(item.image_src)"
                style="width: 240px"
                @click="handleNotePreview(parseImgList(item.image_src))"
                v-if="typeof(parseImgList(item.image_src)) == 'string'"
              />

              <!-- 多张图片 -->
              <swiper :options="swiperOption" style="width: 240px" v-else>
                <swiper-slide v-for="(img,index) in parseImgList(item.image_src)" :key="index">
                  <div class="note-priview-box">
                    <img :src="img" @click="handleNotePreview(img)" />
                  </div>
                </swiper-slide>

                <div class="swiper-pagination" slot="pagination" />
              </swiper>
            </template>

            <Modal v-model="notePreview" footer-hide :mask="false">
              <img :src="imgUrl" v-if="notePreview" style="width: 100%" />
            </Modal>
            <!-- 评论区 -->
            <Collapse simple :value="panelName">
              <Panel :name="item.id.toString()" hide-arrow>
                <div slot="content">
                  <div class="comments-input-box">
                    <Input
                      v-model="commentContent"
                      type="textarea"
                      :rows="2"
                      placeholder="请自觉遵守互联网相关的政策法规，严禁发布色情、暴力、反动的言论。"
                    />
                    <Button
                      type="primary"
                      @click="handleAddComment(user.id,item.id,commentContent)"
                    >
                      发表
                      <br />评论
                    </Button>
                  </div>

                  <!-- 评论列表 -->
                  <List split v-if="commentList">
                    <ListItem v-for="comment in commentList.data" :key="comment.id">
                      <ListItemMeta :avatar="comment.user.avatar" :title="comment.user.nickname">
                        <template slot="description">
                          {{comment.content}}
                          <br />
                          <Time :time="comment.comment_time" interval="1" />
                        </template>
                      </ListItemMeta>
                    </ListItem>

                    <!-- 评论列表尾部 -->
                    <template slot="footer" v-if="commentList.last_page=='1'">已显示全部评论</template>
                    <template slot="footer" v-else>
                      <div @click="showMoreComments" class="show-more">
                        <Icon type="ios-refresh" size="20" />加载更多评论...
                      </div>
                    </template>
                  </List>
                </div>
              </Panel>
            </Collapse>
          </ListItem>

          <!-- 手记列表尾部 -->
          <template slot="footer">没有更多内容了...</template>
          <!-- <template slot="footer" v-if="noteList.last_page=='1'">没有更多内容了...</template>
          <template slot="footer" v-else>
            <div @click="showMoreNotes" class="show-more">
              <Icon type="ios-refresh" size="20" />加载更多...
            </div>
          </template> -->
        </List>
      </div>
    </div>

    <!-- 页面右侧导航栏 -->
    <div class="notes-right">
      <h3>分类检索</h3>
      <Divider />
      <Tree :data="navZoneList" @on-select-change="onZoneSelected" />
    </div>
  </div>
</template>

<script>
import { getUser } from "../utils/mixin";
import _ from "lodash";
import "swiper/dist/css/swiper.css";
import { swiper, swiperSlide } from "vue-awesome-swiper";

export default {
  name: "notes",
  components: {
    swiper,
    swiperSlide
  },
  mixins: [getUser],
  props: [],
  data() {
    return {
      noteContent: "",
      noteList: "",
      commentList: "",
      lastestComment: "",
      nextNotesPage: 2,
      nextCommentsPage: 2,
      paginationUrl: "",
      navZoneList: [
        {
          id: 0,
          title: "最新发布",
          expand: false,
          selected: true
        }
      ],
      zoneList: [],
      noteZone: { id: '', title: "" },
      imgUrl: "",
      uploadPreview: false,
      notePreview: false,
      uploadList: [],
      uploadObject: {},
      loading: false,
      swiperOption: {
        loop: false,
        autoplay: false,
        pagination: {
          el: ".swiper-pagination",
          dynamicBullets: true,
          dynamicMainBullets: 1
        }
      },
      panelName: "",
      commentContent: ""
    };
  },
  mounted() {
    this.loading = true;
    this.axios
      .all([
        this.axios.get("/api/zone"),
        this.axios.get(`/api/note_comment?user=${this.$store.state.uid}`)
      ])
      .then(
        this.axios.spread((zoneRes, commentRes) => {
          this.navZoneList = _.concat(this.navZoneList, zoneRes.data);
          this.zoneList = zoneRes.data;
          this.lastestComment = commentRes.data;
        })
      )
      .catch(err =>
        this.$Notice.error({ title: "交流圈获取失败", desc: error })
      );

    this.fetchData();
  },
  watch: {
    $route: "fetchData"
  },
  methods: {
    fetchData() {
      let zid = this.$route.query.zid;
      if (zid)
        this.axios
          .get(`/api/note?zid=${zid}`)
          .then(noteRes => {
            this.noteList = noteRes.data;
            this.paginationUrl = `/api/note?zid=${zid}`;
          })
          .catch(error =>
            this.$Notice.error({ title: "网络连接失败", desc: error })
          );
      else
        this.axios
          .get("/api/note/")
          .then(noteRes => {
            this.noteList = noteRes.data;
            this.paginationUrl = "/api/note/";
          })
          .catch(error =>
            this.$Notice.error({ title: "网络连接失败", desc: error })
          );
      this.loading = false;
    },
    fetchComments(id) {
      this.axios
        .get(`/api/note_comment?note=${id}`)
        .then(res => {
          this.commentList = res.data;
          this.paginationUrl = `/api/note_comment?note=${id}`;
        })
        .catch(error =>
          this.$Notice.error({ title: "网络连接失败", desc: error })
        );
    },
    onOptionSelected(id, title) {
      this.noteZone.id = id;
      this.noteZone.title = title;
    },
    onZoneSelected(curArray, item) {
      if (item.id == 0) this.$router.push("/notes");
      else this.$router.push(`/notes/?zid=${item.id}`);
    },
    handleNotePreview(url) {
      this.imgUrl = url;
      this.notePreview = true;
    },
    handleUploadPreview(url) {
      this.imgUrl = url;
      this.uploadPreview = true;
    },
    handleRemove(file) {
      // this.uploadList.splice(_.indexOf(this.uploadList,file),1);
      this.$set(this.uploadList, _.pull(this.uploadList, file));
      this.axios.post("/api/del_img/", { url: file });
    },
    handleSuccess(res, file) {
      this.uploadList = _.concat(this.uploadList, res);
      this.uploadObject = Object.assign({}, { url: this.uploadList });
    },
    handleFormatError(file) {
      this.$Notice.warning({
        title: "文件格式错误",
        desc: "文件 " + file.name + " 格式不正确，请选择jpg或png格式的文件"
      });
    },
    handleMaxSize(file) {
      this.$Notice.warning({
        title: "文件过大",
        desc: "文件  " + file.name + " 过大。请上传2M以下的图片"
      });
    },
    handleBeforeUpload() {
      const check = this.uploadList.length < 5;
      if (!check) {
        this.$Notice.warning({
          title: "最多可上传5张图片"
        });
      }
      return check;
    },
    handleTagClose() {
      this.noteZone.id = "";
      this.noteZone.title = "";
    },
    handleReset() {
      this.noteZone = {id: Number};
      this.uploadList = [];
      this.noteContent = "";
    },
    handleSubmit() {
      if (!this.handleBeforeUpload()) return false;
      if (this.noteZone.title == "") {
        this.$Notice.warning({
          title: "请选择所属交流圈"
        });
      } else if (this.noteContent == "") {
        this.$Notice.warning({
          title: "内容不能为空"
        });
      } else {
        this.loading = true;
        this.axios
          .post("/api/note/", {
            uid: this.user.id,
            zid: this.noteZone.id,
            image_src: JSON.stringify(this.uploadObject),
            content: this.noteContent
          })
          .then(res => {
            this.fetchData();
            this.$Notice.success({
              title: "发布成功"
            });
            this.handleReset();
          })
          .catch(err => console.log("err :", err));
      }
    },
    showMoreNotes() {
      this.loading = true;
      this.axios
        .get(`/api/note?page=${this.nextNotesPage++}`)
        .then(res => {
          this.noteList.data = _.concat(this.noteList.data, res.data.data);
          this.loading = false;
        });
    },
    showMoreComments() {
      // 待测试
      this.loading = true;
      this.axios
        .get(this.paginationUrl + `?page=${this.nextCommentsPage++}`)
        .then(res => {
          this.commentList.data = _.concat(
            this.commentList.data,
            res.data.data
          );
          this.loading = false;
        });
    },
    handleThumbsUp() {},
    handleShowComments(id) {
      this.commentList = "";
      this.fetchComments(id);
      if (this.panelName == id) this.panelName = this.panelName == "" ? id : "";
      else {
        this.commentContent = "";
        this.panelName = id;
      }
    },
    handleAddComment(uid, nid, content) {
      this.axios
        .post("/api/note_comment", {
          uid: uid,
          nid: nid,
          content: content
        })
        .then(res => {
          this.fetchComments(nid);
          this.commentContent = "";
          this.$Notice.success({
            title: "评论成功"
          });
        });
    },
    textCut: text => _.truncate(text, { length: 15 }),
    parseImgList: list => JSON.parse(list).url
  }
};
</script>
